package com.sjgtw.cloud.web.rainfall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sjgtw.cloud.common.core.constant.CacheConstants;
import com.sjgtw.cloud.common.core.http.HttpUtils;
import com.sjgtw.cloud.common.core.utils.CommonUtil;
import com.sjgtw.cloud.common.core.utils.DateUtils;
import com.sjgtw.cloud.common.core.utils.SecurityUtils;
import com.sjgtw.cloud.common.core.utils.bean.BeanUtils;
import com.sjgtw.cloud.common.core.web.domain.AjaxResult;
import com.sjgtw.cloud.common.redis.service.RedisService;
import com.sjgtw.cloud.constant.SjgtwConstont;
import com.sjgtw.cloud.service.SystemServerService;
import com.sjgtw.cloud.system.api.model.LoginUser;
import com.sjgtw.cloud.web.rainfall.domain.RainfallInspection;
import com.sjgtw.cloud.web.rainfall.domain.RainfallWarning;
import com.sjgtw.cloud.web.rainfall.mapper.RainfallWarningMapper;
import com.sjgtw.cloud.web.rainfall.service.IRainfallInspectionService;
import com.sjgtw.cloud.web.rainfall.service.IRainfallWarningService;
import com.sjgtw.cloud.web.rainfall.vo.RainfallVO;
import com.sjgtw.cloud.web.rainfallGauge.mapper.RainfallGaugeMapper;
import com.sjgtw.cloud.web.rainfallGauge.vo.RainfallGaugeVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 降雨预警Service业务层处理
 * 
 * @author lvyoufang
 * @date 2024-03-17
 */
@Service
public class RainfallWarningServiceImpl implements IRainfallWarningService 
{
    @Autowired
    private RainfallWarningMapper rainfallWarningMapper;
    @Autowired
    private IRainfallInspectionService inspectionService;
    @Autowired
    private RainfallGaugeMapper gaugeMapper;
    @Autowired
    private SystemServerService systemService;

    @Autowired
    private RedisService redisService;

    @Value("${third.rainfall}")
    private String url;


    /**
     * 查询降雨预警
     * 
     * @param id 降雨预警主键
     * @return 降雨预警
     */
    @Override
    public RainfallWarning selectRainfallWarningById(Long id)
    {
        return rainfallWarningMapper.selectRainfallWarningById(id);
    }

    /**
     * 查询降雨预警列表
     * 
     * @param rainfallWarning 降雨预警
     * @return 降雨预警
     */
    @Override
    public List<RainfallWarning> selectRainfallWarningList(RainfallWarning rainfallWarning)
    {
        return rainfallWarningMapper.selectRainfallWarningList(rainfallWarning);
    }

    /**
     * 新增降雨预警
     * 
     * @param rainfallWarning 降雨预警
     * @return 结果
     */
    @Override
    public int insertRainfallWarning(RainfallWarning rainfallWarning)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        rainfallWarning.setStatus(SjgtwConstont.RainfallWarningStatus.notDispose.getCode());
        rainfallWarning.setCreateUserId(user.getUserid());
        rainfallWarning.setCreateBy(user.getUsername());
        rainfallWarning.setCreateTime(DateUtils.getNowDate());
        return rainfallWarningMapper.insertRainfallWarning(rainfallWarning);
    }

    /**
     * 修改降雨预警
     * 
     * @param rainfallWarning 降雨预警
     * @return 结果
     */
    @Override
    public int updateRainfallWarning(RainfallWarning rainfallWarning)
    {
        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        rainfallWarning.setUpdateBy(user.getUsername());
        rainfallWarning.setUpdateTime(DateUtils.getNowDate());
        return rainfallWarningMapper.updateRainfallWarning(rainfallWarning);
    }

    /**
     * 批量删除降雨预警
     * 
     * @param ids 需要删除的降雨预警主键
     * @return 结果
     */
    @Override
    public int deleteRainfallWarningByIds(String[] ids)
    {
        return rainfallWarningMapper.deleteRainfallWarningByIds(ids);
    }

    /**
     * 删除降雨预警信息
     * 
     * @param id 降雨预警主键
     * @return 结果
     */
    @Override
    public int deleteRainfallWarningById(Long id)
    {
        return rainfallWarningMapper.deleteRainfallWarningById(id);
    }

    @Override
    public void issue(Long id) {
        RainfallWarning rainfallWarning = rainfallWarningMapper.selectRainfallWarningById(id);
        if (rainfallWarning != null && rainfallWarning.getGaugeId() != null) {
            RainfallGaugeVO rainfallGauge = gaugeMapper.selectVoById(rainfallWarning.getGaugeId());
            if (rainfallGauge != null) {
                rainfallWarning.setSectionId(rainfallGauge.getSectionId());
                rainfallWarning.setSection(rainfallGauge.getSection());
                rainfallWarning.setWorkAreaId(rainfallGauge.getWorkAreaId());
                rainfallWarning.setWorkArea(rainfallGauge.getWorkArea());
            }
            rainfallWarning.setTaskType("降雨巡视");
            rainfallWarning.setSystemSoure("应急系统");
            String json = JSONObject.toJSONString(rainfallWarning);
            if(!"testUrl".equals(url)){
                HttpUtils.sendPost(url, json);
            }

        }
    }

    @Override
    public int issue(RainfallWarning rainfallWarning) {
        AjaxResult deptResult = systemService.getDeptById(rainfallWarning.getUnitId());
        AjaxResult userResult = systemService.getUserByIds(rainfallWarning.getResponsibleUserId());
        if (deptResult != null) {
            Object object = deptResult.get("data");
            if (object != null) {
                JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(object));
                if (!json.isEmpty()) {
                    rainfallWarning.setUnitName(json.getString("deptName"));
                }
            }
        }
        if (userResult != null) {
            Object object = userResult.get("data");
            if (object != null) {
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(object));
                if (!jsonArray.isEmpty()) {
                    String userName = "";
                    for (int i=0; i<jsonArray.size();i++) {
                        JSONObject json = jsonArray.getJSONObject(i);
                        userName += json.getString("userName") + ",";
                    }
                    if (userName.length() > 0) {
                        userName = userName.substring(0, userName.length() - 1);
                    }
                    rainfallWarning.setResponsibleUser(userName);
                }
            }
        }
        rainfallWarning.setResponsibleUserId(CommonUtil.addComma(rainfallWarning.getResponsibleUserId()));
        rainfallWarning.setStatus(SjgtwConstont.RainfallWarningStatus.disposing.getCode());

        issue(rainfallWarning.getId());
        return rainfallWarningMapper.updateRainfallWarning(rainfallWarning);
    }

    @Override
    public RainfallVO selectRainfallById(Long id) {
        RainfallWarning rainfallWarning = rainfallWarningMapper.selectRainfallWarningById(id);
        RainfallVO vo = new RainfallVO();
        BeanUtils.copyProperties(rainfallWarning, vo);

        String token = SecurityUtils.getToken();
        String userKey = CacheConstants.LOGIN_TOKEN_KEY + token;
        LoginUser user = redisService.getCacheObject(userKey);

        Long userId = user.getUserid();

        RainfallInspection rainfallInspection = new RainfallInspection();
        rainfallInspection.setCreateUserId(userId);
        rainfallInspection.setRainfallWarningId(id);
        List<RainfallInspection> rainfallInspections = inspectionService.selectRainfallInspectionList(rainfallInspection);
        if (rainfallInspections.size() > 0) {
            RainfallInspection inspection = rainfallInspections.get(0);

            vo.setRainfallWarningId(id);
            vo.setRainfallInspectionId(inspection.getId());
            vo.setInsRange(inspection.getInsRange());
            vo.setMethod(inspection.getMethod());
            vo.setNumber(inspection.getNumber());
            vo.setProblem(inspection.getProblem());
            vo.setSubmited(inspection.getSubmited());
        }
        return vo;
    }

    @Override
    public List<RainfallVO> selectRainfallList(RainfallWarning rainfallWarning) {
        return rainfallWarningMapper.selectRainfallList(rainfallWarning);
    }

    @Override
    @Transactional
    public int deal(RainfallVO vo) {
        RainfallWarning rainfallWarning = rainfallWarningMapper.selectRainfallWarningById(vo.getId());
        rainfallWarning.setStatus(SjgtwConstont.RainfallWarningStatus.disposed.getCode());
        rainfallWarning.setProcessUserIds(vo.getProcessUserIds());
        rainfallWarning.setResponsibleUserId(CommonUtil.addComma(vo.getResponsibleUserId()));
        updateRainfallWarning(rainfallWarning);

        RainfallInspection rainfallInspection = new RainfallInspection();
        BeanUtils.copyProperties(vo, rainfallInspection);
        rainfallInspection.setId(vo.getRainfallInspectionId());
        rainfallInspection.setRainfallWarningId(vo.getId());
        int i = 0;
        if (rainfallInspection.getId() == null) {
            i = inspectionService.insertRainfallInspection(rainfallInspection);
        } else {
            i = inspectionService.updateRainfallInspection(rainfallInspection);
        }

        if (vo.getSubmited()) {
            rainfallInspection.setStatus(SjgtwConstont.RainfallWarningStatus.disposed.getCode());
            rainfallInspection.setTaskType("降雨巡视");
            rainfallInspection.setSystemSoure("应急系统");
            String json = JSONObject.toJSONString(rainfallInspection);
            if(!"testUrl".equals(url)){
                HttpUtils.sendPost(url, json);
            }
        }
        return i;
    }
}
